package x.ovo.wechat.bot.impl.http.request.core;

import lombok.RequiredArgsConstructor;
import x.ovo.wechat.bot.core.exception.LoginException;
import x.ovo.wechat.bot.core.http.request.ApiRequest;
import x.ovo.wechat.bot.core.http.request.BaseRequest;
import x.ovo.wechat.bot.core.util.RegexUtil;
import x.ovo.wechat.bot.core.util.WechatUtil;
import x.ovo.wechat.bot.impl.http.result.CheckLoginResult;

import java.util.function.Function;

@RequiredArgsConstructor
public class SessionRequest extends ApiRequest<BaseRequest> {

    private final CheckLoginResult result;

    @Override
    public ApiRequest<BaseRequest> build() {
        this.url = result.getUrl() + "&fun=new&version=v2";
        this.addHeader("Accept", "application/json, text/plain, */*");
        return this;
    }

    @Override
    protected Function<String, BaseRequest> stringHandler() {
        return s -> {
            BaseRequest request = new BaseRequest();
            if (!"0".equals(RegexUtil.match("<ret>(\\d+)</ret>", s))) {
                throw new LoginException("获取BaseRequest失败: code: " + RegexUtil.match("<ret>(\\d+)</ret>", s) + RegexUtil.match("<message>(\\s+)</message>", s));
            }
            request.setSkey(RegexUtil.match("<skey>(\\S+)</skey>", s));
            request.setSid(RegexUtil.match("<wxsid>(\\S+)</wxsid>", s));
            request.setUin(RegexUtil.match("<wxuin>(\\d+)</wxuin>", s));
            request.setPassTicket(RegexUtil.match("<pass_ticket>(\\S+)</pass_ticket>", s));
            request.setDeviceID(WechatUtil.generateDeviceId());
            return request;
        };
    }
}
